<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>06.浏览器的存储.html</title>
</head>

<body>
    <button id="handlerAddNode">存值</button>
    <button id="handlerGetNode">取值</button>
    <button id="handlerDelNode">删除值</button>

    <script>
        handlerAddNode.onclick = function () {
            const user = {
                name: "小明"
            }
            localStorage.setItem("user", JSON.stringify(user))
            sessionStorage.setItem("user", JSON.stringify(user))
            setCookie("user", JSON.stringify(user),60)

        }
        handlerGetNode.onclick = function () {
            const user = localStorage.getItem("user")
            console.log(JSON.parse(user));
            const user02 = sessionStorage.getItem("user")
            console.log(JSON.parse(user02));
            const user03 = getCookie("user")
            console.log(JSON.parse(user03));

        }
        handlerDelNode.onclick = function () {
            localStorage.removeItem("user")
            sessionStorage.removeItem("user")
            setCookie("user", "",0)
        }
        
        /**
         * 设置cookie值
         */
        function setCookie(cname, cvalue, second) {
            var d = new Date();
            d.setTime(d.getTime() + (second ** 1000));
            var expires = "expires=" + d.toGMTString();
            document.cookie = cname + "=" + cvalue + "; " + expires;
        }
        
        /**
         * 获取cookie
         */
        function getCookie(cname) {
            var name = cname + "=";
            var ca = document.cookie.split(';');
            for (var i = 0; i < ca.length; i++) {
                var c = ca[i].trim();
                if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
            }
            return "";
        }
    </script>

</body>

</html>